package com.annual.system.service.impl;


import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.annual.common.config.WechatConfig;
import com.annual.common.config.WxPayConfig;
import com.annual.common.constant.CacheConstants;
import com.annual.common.core.redis.RedisCache;
import com.annual.common.exception.ServiceException;
import com.annual.system.dto.wechat.WxAccessTokenDto;
import com.annual.system.dto.wechat.WxOpenIdDto;
import com.annual.system.service.IEnterpriseBusinessService;
import com.annual.system.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 业务表 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-12-02
 */
@Service
@Slf4j
public class WechatServiceImpl implements IWechatService {
    @Autowired
    private WechatConfig wechatConfig;
    @Autowired
    private WxPayConfig wxPayConfig;
    @Autowired
    private RedisCache redisCache;
//    @Resource
//    private RestTemplate restTemplate;

    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    public final static String gzh_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    public final static String xcx_openid_url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";


//    /**
//     * 获取接口访问凭证
//     *
//     * @return
//     */
//    @Override
//    public synchronized String getAccessToken() {
//        if(redisCache.hasKey(CacheConstants.GZH_ACCESSTOKEN)){
//            return redisCache.getCacheObject(CacheConstants.GZH_ACCESSTOKEN);
//        }else {
//            String accessToken = "";
//            WxAccessTokenDto accessTokenDto = getGzhAccessToken();
//            if(accessTokenDto!=null && StrUtil.isNotBlank(accessTokenDto.getAccess_token())){
//                accessToken = accessTokenDto.getAccess_token();
//            }else {
//                //如果没有token,那么就去获取，循环5次
//                for (int i = 0; i < 5; i++) {
//                    accessTokenDto = getGzhAccessToken();
//                    if(accessTokenDto!=null && StrUtil.isNotBlank(accessTokenDto.getAccess_token())){
//                        accessToken = accessTokenDto.getAccess_token();
//                        break;
//                    }
//                    ThreadUtil.sleep(1000);
//                }
//            }
//            if(StrUtil.isNotBlank(accessToken)){
//                redisCache.setCacheObject(CacheConstants.GZH_ACCESSTOKEN,accessToken,7100, TimeUnit.SECONDS);
//                return accessToken;
//            }else {
//                throw new ServiceException("微信获取ACCESSTOKEN失败");
//            }
//        }
//    }
//
//    public WxAccessTokenDto getGzhAccessToken(){
//        try {
//            String obj = HttpUtil.get(token_url.replace("APPID", wechatConfig.getAppId()).replace("APPSECRET",  wechatConfig.getAppSecret()));
//            log.info("微信返回TOKEN:{}",obj);
//            if(StrUtil.isNotBlank(obj)){
//                return JSONUtil.toBean(obj, WxAccessTokenDto.class);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        return null;
//    }




    @Override
    public String getOpenId(String code) {
        String appType = wechatConfig.getAppType();
        if(appType.equals("1")){
            return getGzhOpenId(code);
        }else if(appType.equals("2")){
            return getXcxOpenId(code);
        }else {
            throw new ServiceException("暂未开放");
        }
    }


    /**
     * 获取公众号openId
     * @param code
     * @return
     */
    public String getGzhOpenId(String code) {
        String url = String.format(gzh_openid_url, wechatConfig.getAppId(), wechatConfig.getAppSecret(), code);
        String msg = HttpUtil.post(url,"");
        WxOpenIdDto openIdDto = JSONUtil.toBean(msg, WxOpenIdDto.class);
        log.info("code内容：{}",code);
        log.info("获取到的openid结果：{}",msg);
        if(openIdDto.getErrcode() == null){
            return openIdDto.getOpenid();
        }else {
            throw new ServiceException("获取openId失败:"+openIdDto.getErrmsg());
        }
    }


    /**
     * 获取小程序openId
     * @param code
     * @return
     */
    public String getXcxOpenId(String code) {
        String url = String.format(xcx_openid_url,wechatConfig.getAppId(), wechatConfig.getAppSecret(), code);
        log.info("请求地址:{}", xcx_openid_url);
        log.info("微信小程序appid:{}", wechatConfig.getAppId());
        log.info("微信小程序secret:{}", wechatConfig.getAppSecret());
        log.info("微信小程序cede:{}", code);
        String msg = HttpUtil.post(url,"");

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        if(jsonObject.containsKey("openid")){
            return jsonObject.getStr("openid");
        }else {
            log.error("获取openid失败返回:{}",msg);
            throw new ServiceException("获取小程序openid失败");
        }
    }





}
